<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/styles/vs2015.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // 强化jQuery全局可用性
        if (typeof jQuery === 'undefined') {
            throw new Error('jQuery未正确加载');
        }
        window.$ = window.jQuery = jQuery.noConflict(true);
    </script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/highlight.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/languages/python.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/languages/c.min.js"></script>
    <script>hljs.highlightAll();</script>
    <style>
        /* 恢复原始CSS样式 */
        html {
            height: 100%;
        }
        body {
            font-family: 'Consolas', 'Courier New', monospace;
            margin: 0;
            height: 100vh;
            background-color: #1e1e1e;
            color: #d4d4d4;
            display: flex;
            flex-direction: column;
            position: relative;
        }
        #chat-container {
            flex: 1;
            border: 1px solid #3c3c3c;
            margin: 10px;
            overflow-y: auto;
            padding: 10px 5px 70px 10px;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .message {
            padding: 14px 18px;
            border-radius: 15px;
            white-space: pre-wrap;
            word-break: break-word;
            width: fit-content;
            position: relative;
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
            border: 1px solid rgba(255,255,255,0.1);
        }

        .message.user {
            background: linear-gradient(145deg, #e6f3ff, #b3d9ff);
            color: #1a1a1a;
            margin-left: auto;
            margin-right: 10px;
            border-radius: 15px 5px 5px 15px;
            align-self: flex-end;
            max-width: 80%;
            width: fit-content;
            box-sizing: border-box;
            position: relative;
        }

        .message.ai {
            background: linear-gradient(145deg, #383838, #2d2d2d);
            color: #fff;
            margin-right: auto;
            margin-left: 10px;
            border-radius: 5px 15px 15px 5px;
        }

        .message.user::after,
        .message.ai::before {
            content: '';
            position: absolute;
            top: 14px;
            border: 8px solid transparent;
        }

        .message.user::after {
            right: -8px;
            border-left-color: #b3d9ff;
        }

        .message.ai::before {
            left: -8px;
            border-right-color: #383838;
        }

        .message:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(0,0,0,0.25);
        }
        .message.user:hover, .message.ai:hover {
            transform: translateY(-2px);
        }
        .code-block {
            background: rgba(0,0,0,0.3);
            padding: 15px 20px 40px;
            border-radius: 8px;
            margin: 15px 0;
            position: relative;
            border: 1px solid #3c3c3c;
        }
        .code-action-btn {
            position: absolute;
            right: 5px;
            bottom: 5px;
            z-index: 100;
            margin: 0;
            padding: 8px 12px;
            font-size: 13px;
            border-radius: 6px;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            gap: 6px;
            background: linear-gradient(145deg, #2196F3 0%, #1976D2 100%);
            color: white;
            box-shadow: 0 2px 6px rgba(0,0,0,0.3);
        }

        .code-action-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.4);
            background: linear-gradient(145deg, #1976D2 0%, #2196F3 100%);
        }

        .code-action-btn:active {
            transform: translateY(1px);
            box-shadow: 0 1px 3px rgba(0,0,0,0.2);
        }

        .btn-icon {
            font-size: 14px;
            filter: drop-shadow(0 1px 1px rgba(0,0,0,0.2));
        }
        .button-container {
            position: relative;
            height: 28px;
        }
        .code-lang {
            font-weight: 600;
            color: #888;
            margin-bottom: 8px;
            font-size: 0.9em;
            letter-spacing: 0.5px;
            padding-left: 8px;
        }
        #input-container {
            display: flex;
            gap: 10px;
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 10px;
            background-color: #1e1e1e;
            border-top: 1px solid #3c3c3c;
        }
        #message-input {
            flex: 1;
            padding: 8px;
            border: 1px solid #3c3c3c;
            background-color: #252526;
            color: #d4d4d4;
            border-radius: 4px;
        }
        #send-button {
            padding: 8px 16px;
            background-color: #2196F3;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .btn-icon {
            font-size: 14px;
        }
        .execution-result {
            margin: 10px 0;
            padding: 10px;
            border-radius: 4px;
            border-left: 4px solid;
        }
        .execution-result.success {
            background-color: #1e3a1e;
            border-color: #4CAF50;
            color: #d4d4d4;
        }
        .execution-result.error {
            background-color: #3a1e1e;
            border-color: #f44336;
            color: #d4d4d4;
        }
    </style>
</head>
<body>
    <div id="chat-container"></div>
    <div id="input-container">
        <input type="text" id="message-input" placeholder="输入消息...">
        <button id="send-button">发送</button>
        <button id="reset-button" style="background-color: #ff4444">重置对话</button>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', async () => {
            const chatContainer = document.getElementById('chat-container');
            const messageInput = document.getElementById('message-input');
            const sendButton = document.getElementById('send-button');

            // 定义消息添加函数（使用函数声明提升）
            function addMessage(role, content) {
                const messageDiv = document.createElement('div');
                messageDiv.className = `message ${role}-message`;

                // Process code blocks
                let processedContent = content;
                const codeBlocks = content.match(/```([\w-]*)\s*([\s\S]*?)```/g) || [];
                
                codeBlocks.forEach(block => {
                    const langMatch = block.match(/```(\w*)\s*/);
                    const lang = langMatch ? langMatch[1] : '';
                    const code = block.replace(/```(\w*)\s*/, '').replace(/```$/, '');
                    
                    const codeContainer = document.createElement('div');
                    codeContainer.className = 'code-block';
                    
                    if (lang) {
                        const langLabel = document.createElement('div');
                        langLabel.className = 'code-lang';
                        langLabel.textContent = lang.toUpperCase();
                        codeContainer.appendChild(langLabel);

                        const codeElement = document.createElement('pre');
                        const codeNode = document.createElement('code');
                        codeNode.className = lang ? `language-${lang}` : '';
                        codeNode.textContent = code;
                        codeElement.appendChild(codeNode);
                        codeContainer.appendChild(codeElement);

                        const buttonContainer = document.createElement('div');
                        buttonContainer.className = 'button-container';

                        // 复制按钮
                        const copyButton = document.createElement('button');
                        copyButton.className = 'code-action-btn';
                        copyButton.style.right = '65px';
                        copyButton.innerHTML = `
                            <span class="btn-icon">⎘</span>
                            <span class="btn-text">复制</span>
                        `;
                        copyButton.onclick = async () => {
                            try {
                                await navigator.clipboard.writeText(code);
                                copyButton.innerHTML = `
                                    <span class="btn-icon">✓</span>
                                    <span class="btn-text">已复制!</span>
                                `;
                                setTimeout(() => {
                                    copyButton.innerHTML = `
                                        <span class="btn-icon">⎘</span>
                                        <span class="btn-text">复制代码</span>
                                    `;
                                }, 2000);
                            } catch (err) {
                                alert('复制失败，请手动选择代码复制');
                            }
                        };

                        // 应用按钮
                        const applyButton = document.createElement('button');
                        applyButton.className = 'code-action-btn';
                        applyButton.innerHTML = `
                            <span class="btn-icon">⚡</span>
                            <span class="btn-text">应用到节点</span>
                        `;
                        
                        applyButton.addEventListener('click', async () => {
                            console.log('Apply button clicked');
                            applyButton.disabled = true;
                            applyButton.classList.add('loading');
                            try {
                                const response = await fetch('/apply_code', {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/json',
                                    },
                                    body: JSON.stringify({
                                        code: code,
                                        language: lang
                                    })
                                });
                                const result = await response.json();
                                if (result.success) {
                                    const resultDiv = document.createElement('div');
                                    resultDiv.className = 'execution-result success';
                                    resultDiv.innerHTML = `
                                        <h4>✅ 执行成功 (${result.execution_time}s)</h4>
                                        <pre>${result.output || '无输出'}</pre>
                                    `;
                                    codeContainer.parentNode.insertBefore(resultDiv, codeContainer.nextSibling);
                                } else {
                                    const resultDiv = document.createElement('div');
                                    resultDiv.className = 'execution-result error';
                                    resultDiv.innerHTML = `
                                        <h4>❌ 执行失败</h4>
                                        <pre>${result.error || '未知错误'}</pre>
                                    `;
                                    codeContainer.parentNode.insertBefore(resultDiv, codeContainer.nextSibling);
                                }
                            } catch (error) {
                                const resultDiv = document.createElement('div');
                                resultDiv.className = 'execution-result error';
                                resultDiv.innerHTML = `
                                    <h4>⚠️ 网络错误</h4>
                                    <pre>${error.message}</pre>
                                `;
                                codeContainer.parentNode.insertBefore(resultDiv, codeContainer.nextSibling);
                            } finally {
                                applyButton.disabled = false;
                                applyButton.classList.remove('loading');
                            }
                        });
                        
                        buttonContainer.appendChild(copyButton);
                        buttonContainer.appendChild(applyButton);
                        codeContainer.appendChild(buttonContainer);
                    }
                    
                    processedContent = processedContent.replace(block, codeContainer.outerHTML);
                });

                // 使用DOM操作确保正确渲染
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = processedContent;
                while (tempDiv.firstChild) {
                    messageDiv.appendChild(tempDiv.firstChild);
                }
                chatContainer.appendChild(messageDiv);
                
                // 确保滚动到底部
                chatContainer.scrollTo({
                    top: chatContainer.scrollHeight,
                    behavior: 'smooth'
                });

                // 重新初始化代码高亮
                document.querySelectorAll('pre code').forEach((block) => {
                    hljs.highlightElement(block);
                });
            }

            // 加载历史消息
            try {
                const historyResponse = await fetch('/get_history');
                const historyData = await historyResponse.json();
                const messages = Array.isArray(historyData) ? historyData : historyData.messages;
                messages.forEach(msg => {
                    addMessage(msg.role, msg.content);
                });
            } catch (error) {
                console.error('加载历史记录失败:', error);
            }

            // 初始化代码高亮
            hljs.highlightAll();

            // 发送消息函数
            const sendMessage = async () => {
                const message = messageInput.value.trim();
                if (!message) return;

                addMessage('user', message);
                messageInput.value = '';

                try {
                    const response = await fetch('/chat', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ message })
                    });

                    const data = await response.json();
                    if (data.response) {
                        addMessage('ai', data.response);
                    } else if (data.error) {
                        addMessage('ai', `Error: ${data.error}`);
                    }
                } catch (error) {
                    addMessage('ai', `Network error: ${error.message}`);
                }
            };

            // 事件监听
            sendButton.addEventListener('click', sendMessage);
            messageInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    sendMessage();
                }
            });

            // 重置按钮功能
            document.getElementById('reset-button').addEventListener('click', async () => {
                try {
                    const response = await fetch('/reset_chat', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        }
                    });
                    
                    const result = await response.json();
                    if (result.success) {
                        chatContainer.innerHTML = '';
                        addMessage('system', '对话历史已重置');
                    } else {
                        addMessage('system', `重置失败: ${result.error || '未知错误'}`);
                    }
                } catch (error) {
                    addMessage('system', `网络错误: ${error.message}`);
                }
            });
        });
    </script>
</body>
</html>
